package com.lian.community.controller.like;

import com.lian.community.async.EventModel;
import com.lian.community.async.EventProducer;
import com.lian.community.constant.EventType;
import com.lian.community.constant.ResponseCode;
import com.lian.community.entity.user.HostUser;
import com.lian.community.entity.user.User;
import com.lian.community.exception.ParamIllegalException;
import com.lian.community.service.like.LikeService;
import com.lian.community.util.JsonUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;

import java.util.Map;

@Controller
public class LikeController {
    @Autowired
    LikeService likeService;

    @Autowired
    HostUser hostUser;

    @Autowired
    EventProducer eventProducer;

    @RequestMapping(value = "/like")
    public String like(@RequestParam int entityId, @RequestParam int entityType){
        Long count;
        Map<String,Object> map = hostUser.getValue();
        User user = (User)map.get("user");
        Integer userId = user.getId();
        try {
            count = likeService.like(entityId, entityType, userId);
            eventProducer.add(new EventModel(EventType.LIKE).setActorId(userId).setEntityId(entityId).setEntityType(entityType));

        } catch (ParamIllegalException e) {
            e.printStackTrace();
            return JsonUtil.getJsonString(ResponseCode.PARAM_ILLEGAL, e.getMessage());
        } catch (Exception e) {
            e.printStackTrace();
            return JsonUtil.getJsonString(ResponseCode.SERVER_ERROR, "系统出错!");
        }
        return JsonUtil.getJsonString(ResponseCode.REQUEST_SUCCEED, String.valueOf(count));

    }

    @RequestMapping(value = "/disLike")
    public String disLike(@RequestParam int entityId, @RequestParam int entityType){
        Long count;
        Map<String,Object> map = hostUser.getValue();
        User user = (User)map.get("user");
        Integer userId = user.getId();
        try {
            count = likeService.disLike(entityId, entityType, userId);
        } catch (ParamIllegalException e) {
            e.printStackTrace();
            return JsonUtil.getJsonString(ResponseCode.PARAM_ILLEGAL, e.getMessage());
        } catch (Exception e) {
            e.printStackTrace();
            return JsonUtil.getJsonString(ResponseCode.SERVER_ERROR, "系统出错!");
        }
        return JsonUtil.getJsonString(ResponseCode.REQUEST_SUCCEED, String.valueOf(count));

    }

}
